/**
 * Created by hyczzhu on 11/20/15.
 */

const webpack = require('webpack');
const fs = require('fs');
const path = require('path');

let commonJsDeps = [];
fs.readdirSync('node_modules')
    .filter(function (x) {
        return ['.bin'].indexOf(x) === -1;
    })
    .forEach(function (mod) {
        commonJsDeps.push(mod);
    });

commonJsDeps = commonJsDeps.concat([
    'request-promise/errors',
]);

const configValue = {
    node: {
        __filename: true,
        __dirname: true
    },
    entry: {
        'server': path.resolve(__dirname, './src/server/server.js'),
        'wechat-server': path.resolve(__dirname, './src/server/wechat.js'),
    },
    output: {
        filename: 'server/[name].js',
        path: path.resolve(__dirname, './dist'),
    },
    resolve: { // 设置模块如何被解析
        alias: {
            '@biztools': path.resolve(__dirname, './src/biztools'),
            '@components': path.resolve(__dirname, './src/components'),
            '@styles': path.resolve(__dirname, './src/styles'),
            '@store': path.resolve(__dirname, './src/store'),
            '@router': path.resolve(__dirname, './src/router'),
            '@assets': path.resolve(__dirname, './assets'),
            '@common': path.resolve(__dirname, './src/common'),
            '@server': path.resolve(__dirname, './src/server'),
            '@config': path.resolve(__dirname, './src/server/config'),
            '@views': path.resolve(__dirname, './src/views'),
            '@mock': path.resolve(__dirname, './src/mock'),
            '@constants': path.resolve(__dirname, './src/constants'),
            '@mixins': path.resolve(__dirname, './src/pages/page.js'),
            '@vuex': path.resolve(__dirname, './src/store'),
        },
        extensions: ['*', '.js']
    },
    target: 'node',
    module: {
        rules: [
            {
                test: /\.js$/,
                use: 'babel-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.json$/,
                use: ['json-loader'],
            },
        ]
    },
    externals: [
        (context, request, callback) => {
            if (commonJsDeps.indexOf(request) >= 0) {
                callback(null, `commonjs ${request}`);
                return;
            }
            callback();
        },
    ],
    plugins: [
        new webpack.BannerPlugin({
            banner: 'require("source-map-support").install();',
            raw: true,
            entryOnly: false,
        }),
    ]
};

const env = process.env.BUILD_MODE.trim();

if (env === 'dev') {
    configValue.devtool = 'source-map';
    configValue.mode = 'development';
}
if (env === 'prod') {
    configValue.mode = 'production';
}

module.exports = configValue;
